//
//  MyView.m
//  Dispatch
//
//  Created by hyeyeon on 14. 1. 14..
//  Copyright (c) 2014년 hyeyeon. All rights reserved.
//

#import "MyView.h"

#define frameTable CGRectMake(20, followButton.frame.origin.y+followButton.frame.size.height, mySize.width-40, myRect.size.height-followButton.frame.origin.y-followButton.frame.size.height-10)

@implementation MyView
@synthesize followList, issueArray, responseData, selectArray, imageURL, noticeNewIcon;
@synthesize followButton, issueButton, settingButton;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        myRect = frame;
        appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        self.responseData = [NSMutableData data];
        self.backgroundColor = ColorFromRGB(0x413c43);
        issueArray = [[NSMutableArray alloc] init];
        currentPage = 1;
        
        [self makeObject];
    }
    return self;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

#pragma mark - 진입
-(void)appearView{
    if (followButton.selected) {
        if (!duringNetwork) {
            
            [self requestFollowList];
        }
    }else if (issueButton.selected){
        if (!duringNetwork) {
            if ([self.issueArray count] <= 0) {
                
                [self requestInterestIssueWithPage:1];
            }
        }
    }else if (settingButton.selected){
        [self requestCheckNotice];
    }
}

#pragma mark - 메뉴버튼
-(void)makeObject{
    self.backgroundColor = ColorFromRGB(0x4d4d57);

    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, mySize.width-20, myRect.size.height-20)];
    bgView.backgroundColor = ColorFromRGB(0xf2f2f2);
    [self addSubview:bgView];
    
    //메뉴버튼
    followButton = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 93, 29)];
    [followButton setBackgroundImage:[UIImage imageNamed:@"submenu_follow"] forState:UIControlStateNormal];
    [followButton setBackgroundImage:[UIImage imageNamed:@"submenu_follow_on"] forState:UIControlStateSelected];
    [followButton addTarget:self action:@selector(followButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [followButton setTitle:@"Follow" forState:UIControlStateNormal];
    [followButton setTitleColor:ColorFromRGB(0x49a1d9) forState:UIControlStateNormal];
    [followButton setTitleColor:ColorFromRGB(0xffffff) forState:UIControlStateSelected];
    [followButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self addSubview:followButton];
    
    
    issueButton = [[UIButton alloc] initWithFrame:CGRectMake(followButton.frame.origin.x+followButton.frame.size.width, 20, 93, 29)];
    [issueButton setBackgroundImage:[UIImage imageNamed:@"submenu_issue"] forState:UIControlStateNormal];
    [issueButton setBackgroundImage:[UIImage imageNamed:@"submenu_issue_on"] forState:UIControlStateSelected];
    [issueButton addTarget:self action:@selector(issueButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [issueButton setTitle:NSLocalizedString(@"setting_issue", @"") forState:UIControlStateNormal];
    [issueButton setTitleColor:ColorFromRGB(0x49a1d9) forState:UIControlStateNormal];
    [issueButton setTitleColor:ColorFromRGB(0xffffff) forState:UIControlStateSelected];
    [issueButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [self addSubview:issueButton];
    
    
    
    
    settingButton = [[UIButton alloc] initWithFrame:CGRectMake(issueButton.frame.origin.x+issueButton.frame.size.width, 20, 93, 29)];
    [settingButton setBackgroundImage:[UIImage imageNamed:@"submenu_setting"] forState:UIControlStateNormal];
    [settingButton setBackgroundImage:[UIImage imageNamed:@"submenu_setting_on"] forState:UIControlStateSelected];
    [settingButton setTitle:NSLocalizedString(@"setting", @"") forState:UIControlStateNormal];
    [settingButton setTitleColor:ColorFromRGB(0x49a1d9) forState:UIControlStateNormal];
    [settingButton setTitleColor:ColorFromRGB(0xffffff) forState:UIControlStateSelected];
    [settingButton.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [settingButton addTarget:self action:@selector(settingButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:settingButton];
    
    [self followButtonAction:followButton];
}

-(void)followButtonAction:(id)sender{
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_MY Label:ANA_LAB_My_Follow];
    
    followButton.selected = YES;
    issueButton.selected = settingButton.selected = NO;
    followTable.hidden = NO;
    issueTable.hidden = settingTable.hidden = YES;
    
    if (!followTable) {
        followTable = [[UITableView alloc] initWithFrame:frameTable];
        followTable.delegate = self;
        followTable.dataSource = self;
        followTable.tag = 1;
        followTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        followTable.backgroundColor = [UIColor clearColor];
        followTable.showsHorizontalScrollIndicator = NO;
        followTable.showsVerticalScrollIndicator = NO;

        [self addSubview:followTable];
        
        selectArray = [[NSMutableArray alloc] init];
        followList = [[NSMutableArray alloc] init];
    }
    [self bringSubviewToFront:followTable];
    
    if (!duringNetwork) {
        
        [self requestFollowList];
    }
}

-(void)issueButtonAction:(id)sender{
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_MY Label:ANA_LAB_My_Issue];
    
    issueButton.selected = YES;
    followButton.selected = settingButton.selected = NO;
    issueTable.hidden = NO;
    followTable.hidden = settingTable.hidden = YES;
    
    
    if (!issueTable) {
        issueTable = [[UITableView alloc] initWithFrame:frameTable];
        issueTable.delegate = self;
        issueTable.dataSource = self;
        issueTable.tag = 2;
        issueTable.backgroundColor = [UIColor clearColor];
//        issueTable.showsHorizontalScrollIndicator = NO;
//        issueTable.showsVerticalScrollIndicator = NO;
        [self addSubview:issueTable];
    }
    [self bringSubviewToFront:issueTable];
    
    if (!duringNetwork) {
        
        if ([self.issueArray count] <= 0) {
            
            [self requestInterestIssueWithPage:1];
        }
    }
}

-(void)settingButtonAction:(id)sender{
    
    
    [appDelegate analyticsCategory:ANA_CAT_PAGE Action:ANA_ACT_MY Label:ANA_LAB_My_Setting];
    
    settingButton.selected = YES;
    followButton.selected = issueButton.selected = NO;
    settingTable.hidden = NO;
    issueTable.hidden = followTable.hidden = YES;
    
    
    if (!settingTable) {
        settingTable = [[UITableView alloc] initWithFrame:frameTable];
        settingTable.delegate = self;
        settingTable.dataSource = self;
        settingTable.tag = 3;
        settingTable.backgroundColor = [UIColor clearColor];
        [self addSubview:settingTable];
    }
    settingTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self bringSubviewToFront:settingTable];
    
    if (!duringNetwork) {
        [self requestCheckNotice];
    }
}

#pragma mark - 크레딧
-(void)makeCreditView{
    
    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
    
    creditView = [[CommonView alloc] initWithFrame:CGRectMake(0, myOrginY, mySize.width, mySize.height-20)];
    [viewController.view addSubview:creditView];
    
    creditView.titleLabel.text = @"Credit";
    [creditView.backButton addTarget:self action:@selector(creditBackButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    creditView.bodyView.backgroundColor = ColorFromRGB(0x413c43);
    
    NSArray *textArray = [NSArray arrayWithObjects:
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"김창혁",@"배하석", nil],@"name",@"백엔드 엔지니어링",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"권상훈",@"박혜연", nil],@"name",@"프론트엔드 엔지니어링",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:@"공은령",@"김영주",@"홍정은", nil],@"name",@"크레이티브 디자인",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"이윤희"],@"name",@"앱 퍼블리싱",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"강경서"],@"name",@"서비스 기획",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"김경민"],@"name",@"기획팀장",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"오수경"],@"name",@"개발팀장",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"정향미"],@"name",@"디자인팀장",@"position", nil],
                          [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"박세현"],@"name",@"서비스기획본부장",@"position", nil]
                          ,nil];

    float y = deviceIOS7 ? 44 : 20;
    UIView *textBgView = [[UIView alloc] initWithFrame:CGRectMake(37, y, mySize.width-37, creditView.bodyView.frame.size.height)];
    [creditView.bodyView addSubview:textBgView];
    
    
    for (int i = 0; i<[textArray count]; i++) {
        UILabel *position = [[UILabel alloc] initWithFrame:CGRectMake(0, 40*i, textBgView.frame.size.width, 15)];
        position.backgroundColor = [UIColor clearColor];
        position.textColor = ColorFromRGB(0x49a1d9);
        position.font = [UIFont systemFontOfSize:11];
        position.text = [[textArray objectAtIndex:i] objectForKey:@"position"];
        [textBgView addSubview:position];
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(0, (40*i)+15, position.frame.size.width, position.frame.size.height)];
        name.backgroundColor = [UIColor clearColor];
        name.textColor = ColorFromRGB(0xe9e9e9);
        name.font = [UIFont systemFontOfSize:11];
        
        NSString *nameStr = @"";
        NSArray *array = [[textArray objectAtIndex:i] objectForKey:@"name"];
        for (int j = 0; j<array.count; j++) {
            if (j == 0) {
                
                nameStr = [nameStr stringByAppendingString:[array objectAtIndex:j]];
            }else{
                nameStr = [nameStr stringByAppendingString:[NSString stringWithFormat:@", %@",[array objectAtIndex:j]]];
            }
        }
        NSLog(@"name str : %@",nameStr);
        
        name.text = nameStr;
        [textBgView addSubview:name];
    }
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(creditView.bodyView.frame.size.width-135, 35, 135, 210)];
    image.image = [UIImage imageNamed:@"version_icon"];
    [creditView.bodyView addSubview:image];
    
    UILabel *logo = [[UILabel alloc] initWithFrame:CGRectMake(0, creditView.bodyView.frame.size.height-y, creditView.bodyView.frame.size.width, 15)];
    logo.backgroundColor = [UIColor clearColor];
    logo.textColor = ColorFromRGB(0xe9e9e9);
    logo.font = [UIFont systemFontOfSize:10];
    logo.text = @"MezzoMedia All rights reserved";
    logo.textAlignment = NSTextAlignmentCenter;
    [creditView.bodyView addSubview:logo];
    
    
}

-(void)appearCredit{
    if (!creditView) {
        [self makeCreditView];
    }
    
    creditView.frame = CGRectMake(mySize.width, creditView.frame.origin.y, creditView.frame.size.width, creditView.frame.size.height);
    
    [UIView animateWithDuration:0.3f animations:^{
        creditView.frame = CGRectMake(0, creditView.frame.origin.y, creditView.frame.size.width, creditView.frame.size.height);
    }];
}

-(void)creditBackButtonAction:(id)sender{
    
    if (creditView) {
        
        creditView.frame = CGRectMake(0, creditView.frame.origin.y, creditView.frame.size.width, creditView.frame.size.height);
        [UIView animateWithDuration:0.3f animations:^{
            
            creditView.frame = CGRectMake(mySize.width, creditView.frame.origin.y, creditView.frame.size.width, creditView.frame.size.height);
        } completion:^(BOOL finished) {
            [creditView removeFromSuperview];
            creditView = nil;
        }];
    }
}

#pragma mark - 공지사항WEb

-(void)makeNoticeView{
    
    ViewController *vController = (ViewController*)appDelegate.window.rootViewController;
    noticeView = [[CommonView alloc] initWithFrame:CGRectMake(0, myOrginY, mySize.width, mySize.height-20)];
    
    noticeView.titleLabel.text = NSLocalizedString(@"Notice", @"");
    [noticeView.backButton addTarget:self action:@selector(noticeBackButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIWebView *notiWeb = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, noticeView.bodyView.frame.size.width, noticeView.bodyView.frame.size.height)];
    notiWeb.backgroundColor = ColorFromRGB(0xffffff);
    [notiWeb setScalesPageToFit:YES];
    notiWeb.delegate = self;
    notiWeb.scrollView.delegate = self;
    NSURL *url = [NSURL URLWithString:@"http://dispatchapi.mapps.kr/notice.php"];
    [notiWeb loadRequest:[NSURLRequest requestWithURL:url]];
    
    [noticeView.bodyView addSubview:notiWeb];
    [vController.view addSubview:noticeView];
    
    
}

-(void)appearNoticeView{
    
    self.noticeNewIcon = nil;
    
    if (!noticeView) {
        [self makeNoticeView];
    }
    noticeView.frame = CGRectMake(mySize.width, noticeView.frame.origin.y, noticeView.frame.size.width, noticeView.frame.size.height);
    
    [UIView animateWithDuration:0.3f animations:^{
        noticeView.frame = CGRectMake(0, noticeView.frame.origin.y, noticeView.frame.size.width, noticeView.frame.size.height);
    }];

}

-(void)noticeBackButtonAction:(id)sender{
    if (noticeView) {
        
        noticeView.frame = CGRectMake(0, noticeView.frame.origin.y, noticeView.frame.size.width, noticeView.frame.size.height);
        [UIView animateWithDuration:0.3f animations:^{
            
            noticeView.frame = CGRectMake(mySize.width, noticeView.frame.origin.y, noticeView.frame.size.width, noticeView.frame.size.height);
        } completion:^(BOOL finished) {
            [noticeView removeFromSuperview];
            noticeView = nil;
        }];
    }
    
    [settingTable reloadData];
}

#pragma mark - UIWebView Delegate
-(void)webViewDidStartLoad:(UIWebView *)webView{
}

-(void)webViewDidFinishLoad:(UIWebView *)webView{
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    return YES;
}


#pragma mark - 노티수신여부
-(void)notiYes:(BOOL)yn onType:(NSInteger)index{
    //index : 2=뉴스속보 3=스타속보 4=배틀안내 5=관심뉴스
    
    NSString *analyticsLabel = @"";
//    if (!duringNetwork) {
    
        NSString *string = @"";
        switch (index) {
            case 2:
                string = @"news";
                analyticsLabel = yn ? ANA_LAB_C_Newsalarm_On : ANA_LAB_C_Newsalarm_Off;
                break;
            case 3:
                string = @"star";
                analyticsLabel = yn ? ANA_LAB_C_Followalarm_On : ANA_LAB_C_Followalarm_Off;
                break;
            case 4:
                string = @"battle";
                analyticsLabel = yn ? ANA_LAB_C_Battlealarm_On : ANA_LAB_C_Battlealarm_Off;
                break;
            case 5:
                string = @"my";
                analyticsLabel = yn ? ANA_LAB_C_Issuealarm_On : ANA_LAB_C_Issuealarm_Off;
                break;
            default:
                break;
        }
        
        [appDelegate analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_COMMON Label:analyticsLabel];
        [self requestNotiSettingOfType:string andYes:yn];
//    }else{
//        //로딩중
//    }
}


#pragma mark - 페이지

-(void)loadNextPage{
    
    if (isEnd) {
        
        currentPage++;
        
    }else{
        //마지막페이지임
    }
}

#pragma mark - 네트워크
//팔로우 리스트 부르기
-(void)requestFollowList{
    
    if (duringNetwork) {
        return;
    }
    
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    networkIndex = 1;
    NSString *dataStr = [NSString stringWithFormat:@"deviceid=%@&lang=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_FOLLOWLIST,dataStr];
    [self requestURL:url];
}

//팔루오&언팔로우
-(void)requestFollow:(BOOL)yn andStarID:(NSString*)starID{

    networkIndex = 2;
    [appDelegate appearActivityOnPoint:CGPointMake(mySize.width*0.5f, mySize.height*0.5f)];
    [appDelegate analyticsCategory:ANA_CAT_CLICK Action:ANA_ACT_COMMON Label:ANA_LAB_C_Unfollow];

    NSString *dataStr = [NSString stringWithFormat:@"deviceid=%@&star_id=%@&follow=%d&lang=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],starID,yn?1:0,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_FOLLOW,dataStr];
    

    [self requestURL:url];
}

//관심이슈부르기

-(void)requestInterestIssueWithPage:(NSInteger)page{
    
    if (duringNetwork) {
        return;
    }
    
    currentPage = page;
    networkIndex = 3;
    NSString *dataStr = [NSString stringWithFormat:@"deviceid=%@&lang=%@&page=%d&pagesize=100",[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],appDelegate.currentLanguage,page];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_INTEREST_ISSUE,dataStr];
    [self requestURL:url];
}

//샛팅화면 내 공지사항 신규항복
-(void)requestCheckNotice{
    
    if (duringNetwork) {
        return;
    }
    
    networkIndex = 4;
//    int timestamp = [[NSDate date] timeIntervalSince1970];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSDate *date = [NSDate date];
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    
    NSString *dataStr = [NSString stringWithFormat:@"timestamp=%@&lang=%@", dateStr,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_CHECK_NOTICE, dataStr];
    [self requestURL:url];
}

//노티 수신여부
-(void)requestNotiSettingOfType:(NSString*)type andYes:(BOOL)yn{
    networkIndex = 5;
    NSString *dataStr = [NSString stringWithFormat:@"deviceid=%@&status=%d&type=%@&lang=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"uuid"],yn?1:0,type,appDelegate.currentLanguage];
    dataStr = [appDelegate encryptDataURLString:dataStr];
    NSString *url = [NSString stringWithFormat:@"%@?p=%@",URL_NOTI,dataStr];
    [self requestURL:url];
}

-(void)requestURL:(NSString*)url{
    
    [self performSelectorOnMainThread:@selector(startRequestWithURL:) withObject:url waitUntilDone:NO];
}

-(void)startRequestWithURL:(NSString*)url{
    @autoreleasepool {
        
        duringNetwork = YES;
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        if (url) {
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
            [request setHTTPMethod:@"POST"];
            
            NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            
            if(connection){
                NSLog(@"MY리스트 요청 : %@",url);
            }
            
        }
    }
}

#pragma mark Delegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.responseData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connectio{
    
    duringNetwork = NO;
    [appDelegate removeActivity];
    
    NSString *currentRequestString = [NSString stringWithFormat:@"%@",connectio.currentRequest];
    
    NSError *myError = nil;
    NSDictionary *resultDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    NSLog(@"resultDictionary : %@",resultDictionary);
    
    if ([currentRequestString rangeOfString:URL_FOLLOWLIST].location != NSNotFound) {
        //팔뤄리스트
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                resultDictionary = [resultDictionary objectForKey:@"data"];
                [self.followList setArray:[resultDictionary objectForKey:@"items"]];
                
                [followTable reloadData];
            }
        }
    }else if([currentRequestString rangeOfString:URL_FOLLOW].location != NSNotFound){
        //언팔로우함
        
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                //재대로 언팔됨
                
                int index = 0;
                while (index < [self.followList count]) {
                    
                    NSString *string = [[self.followList objectAtIndex:index] objectForKey:@"star_id"];
                    NSLog(@"f_string : %@",string);
                    if ([self.selectArray containsObject:string]) {
                        
                        [self.followList removeObject:[self.followList objectAtIndex:index]];
                    }else{
                        index++;
                    }
                }
                
//                for (int i = 0; i<[self.followList count]; i++) {
//                    
//                    NSString *string = [[self.followList objectAtIndex:i] objectForKey:@"star_id"];
//                    NSLog(@"f_string : %@",string);
//                    if ([self.selectArray containsObject:string]) {
//                        
//                        [self.followList removeObject:[self.followList objectAtIndex:i]];
//                    }
//                }
                [self.selectArray removeAllObjects];
                
                
                [followTable reloadData];
            }else{
                //1:인원초과, 9:파라미터에러
            }
        }
    }else if([currentRequestString rangeOfString:URL_INTEREST_ISSUE].location != NSNotFound){
        
        //관심이슈
        
        self.imageURL = [resultDictionary objectForKey:@"imgurl"];
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                if (currentPage == 1) {
                    [self.issueArray removeAllObjects];
                }
                
                resultDictionary = [resultDictionary objectForKey:@"data"];
                
                NSArray *items = ([appDelegate checkObject:[resultDictionary objectForKey:@"items"]]) ? [resultDictionary objectForKey:@"items"] : nil;
                if (items) {
                    [self.issueArray addObjectsFromArray:items];
                }
                NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
                [notification postNotificationName:ITEM_LIST_LOAD object:self.issueArray];
                
                isEnd = ([appDelegate checkObject:[resultDictionary objectForKey:@"isend"]]) ? [[resultDictionary objectForKey:@"isend"] boolValue] : NO;

            }
            
            [issueTable reloadData];
        }
    }else if([currentRequestString rangeOfString:URL_CHECK_NOTICE].location != NSNotFound){
        //셋팅화면 내 공지사항 신규항목
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                resultDictionary = [resultDictionary objectForKey:@"data"];
                if (resultDictionary) {
                    
                    NSInteger exist = ([appDelegate checkObject:[resultDictionary objectForKey:@"new_notice"]]) ? [[resultDictionary objectForKey:@"new_notice"] integerValue] : 0;
                    if (exist == 1) {
                        self.noticeNewIcon = [UIImage imageNamed:@"icon_new"];
                        [settingTable reloadData];
                    }else{
                        self.noticeNewIcon = nil;
                    }
                }
            }
        }
    }else if([currentRequestString rangeOfString:URL_NOTI].location != NSNotFound){
        //노티 수신여부
        
        if ([resultDictionary objectForKey:@"return_code"]) {
            if ([[resultDictionary objectForKey:@"return_code"] intValue] == 0){
                
                resultDictionary = [[resultDictionary objectForKey:@"data"] objectForKey:@"noti_status"];
                
                if ([appDelegate checkObject:[resultDictionary objectForKey:@"news"]]) {
                    
                    BOOL news = [[resultDictionary objectForKey:@"news"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:news forKey:UD_ALARM_NEWS];
                    
                }else if ([appDelegate checkObject:[resultDictionary objectForKey:@"star"]]){
                    
                    BOOL star = [[resultDictionary objectForKey:@"star"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:star forKey:UD_ALARM_STAR];
                }else if ([appDelegate checkObject:[resultDictionary objectForKey:@"battle"]]){
                    
                    BOOL battle = [[resultDictionary objectForKey:@"battle"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:battle forKey:UD_ALARM_BATTLE];
                    
                }else if ([appDelegate checkObject:[resultDictionary objectForKey:@"my"]]){
                    
                    BOOL my = [[resultDictionary objectForKey:@"my"] boolValue];
                    [[NSUserDefaults standardUserDefaults] setBool:my forKey:UD_ALARM_MY];
                }
                
            }
        }
    }
    
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    duringNetwork = NO;
    NSLog(@"MY 네트워크 요청 실패 : %@",error);
}

#pragma mark - 언팔로우
-(void)unfollowClick:(id)sender{
    
    NSString *starId = @"";
    for (int i = 0; i<[self.selectArray count]; i++) {
        NSString *string = [self.selectArray objectAtIndex:i];
        if (i == 0) {
            starId = [starId stringByAppendingString:string];
        }else{
            starId = [starId stringByAppendingString:[NSString stringWithFormat:@"_%@",string]];
        }
    }
    [self requestFollow:NO andStarID:starId];
}

#pragma mark - UITableView Delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView.tag == 1) {
        //퐐롱
        return 2;
    }else if(tableView.tag == 2){
        return 1;   //관심이슈
    }
    else if(tableView.tag == 3){
        //설정
        return 2;
    }else{
        return 1;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 1) {
        if (section == 0) {
            return 1;   //팔로우의 "언팔로우"버튼있는곳
        }else{
            return [self.followList count];
        }
    }else if(tableView.tag == 2){
        return [self.issueArray count];
    }
    else if(tableView.tag == 3){
        if (section == 0) {
            return 9;
        }
        else{
            return 1;   //약관
        }
    }
    else{
        return 10;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 1) {
        return 35;
    }else if(tableView.tag == 2){
        return 90;
    }else if(tableView.tag == 3){
        if (indexPath.section == 0) {
            
            return 40;
        }else{
            return 230;
        }
    }else{
        return 44;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView.tag == 1) {
        
        static NSString *CellIdentifier = @"MyViewFollowTableCell";
        FollowTableViewCell *cell = (FollowTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[FollowTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.delegate = self;
        }
        
        if (indexPath.section == 0) {
            //언팔로우 버튼
            [cell appearUnfollow];
        }else{
            
            BOOL yn = [self.selectArray containsObject:[[self.followList objectAtIndex:indexPath.row] objectForKey:@"star_id"]];
            [cell appearStarName:[[self.followList objectAtIndex:indexPath.row] objectForKey:@"name"] andID:[[self.followList objectAtIndex:indexPath.row] objectForKey:@"star_id"] andCheck:yn];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else if(tableView.tag == 2){
        static NSString *CellIdentifier = @"MyIssueTableCell";
        MyIssueTableViewCell *cell = (MyIssueTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[MyIssueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.delegate = self;
        }
        
        //api없어서 아직 작업못함
        
        cell.photoImage.tag = indexPath.row;
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = [self.issueArray objectAtIndex:indexPath.row];
        NSString *contentID = [dic objectForKey:@"content_id"];
        NSString *newsURL = [dic objectForKey:@"news_url"];
        NSString *title = [dic objectForKey:@"title"];
        NSString *mediaType = [appDelegate setMediaType:[dic objectForKey:@"media_type"]];
        NSString *date = [dic objectForKey:@"date"];
        NSString *thumbURL = [dic objectForKey:@"thumb_url"];
        NSString *name = [dic objectForKey:@"name"];
        NSInteger voteStatus = [[dic objectForKey:@"vote_status"] integerValue];
        NSString *upCnt = [dic objectForKey:@"up_cnt"];
        NSString *downCnt = [dic objectForKey:@"down_cnt"];
        
        
        [cell setDate:date andMediaType:mediaType andTitle:title andStar:name andUpClick:(voteStatus == 1) andDownClick:(voteStatus == 2)andUpCount:upCnt andDownCount:downCnt];
        
        
        [appDelegate loadAsyncImageFromDomain:self.imageURL andFileName:thumbURL imageBlock:^(UIImage *image) {
            
            if (cell.photoImage.tag == indexPath.row) {
                cell.photoImage.image = image;
                [appDelegate effectFaceoutTargetView:cell.photoImage];
            }
            
        } errorBlock:^{
            
            NSLog(@"검색>이슈 이미지호출 실패");
        }];
        return cell;
        
    }
    else if(tableView.tag == 3){
        
        if (indexPath.section == 0) {
            
            //설정
            static NSString *CellIdentifier = @"SettingTableCell";
            SettingTableViewCell *cell = (SettingTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[SettingTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.delegate = self;
                

            }
            
            if (indexPath.section == 0) {
                
                NSArray *array = [NSArray arrayWithObjects:
                                  NSLocalizedString(@"Notice", @""),                //공지
                                  NSLocalizedString(@"Push Notification", @""),     //알람
                                  NSLocalizedString(@"Breaking", @""),              //속보
                                  NSLocalizedString(@"Follow_Star", @""),           //팔로우스타속보
                                  NSLocalizedString(@"Stat_battle", @""),           //배틀1등안내
                                  NSLocalizedString(@"My_interest", @""),           //관심뉴스
                                  NSLocalizedString(@"EmptyTheMemory", @""),        //캐시지우기
                                  NSLocalizedString(@"EmailToOperator", @""),       //제휴문의
                                  NSLocalizedString(@"Version", @""),               //버전
                                  nil];
                
                
                BOOL check = (indexPath.row == 2 || indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 5);
                BOOL remove = (indexPath.row == 6);
                
                cell.mIndex = indexPath.row;
                [cell setString:[array objectAtIndex:indexPath.row] andCheckButtonHidden:!check andremoveButtonHidden:!remove];
                
                cell.iconImage.hidden = YES;
                if (indexPath.row == 0) {
                    //공지사항
                    if (self.noticeNewIcon) {
                        
                        cell.iconImage.image = self.noticeNewIcon;
                        cell.iconImage.hidden = NO;
                        cell.iconImage.frame = CGRectMake([[array objectAtIndex:indexPath.row] length]*14, 5, 14, 14);
                    }
                }
                else if (indexPath.row == 2) {
                    //속보
                    cell.checkButton.selected = [[NSUserDefaults standardUserDefaults] boolForKey:UD_ALARM_NEWS];
                }else if(indexPath.row == 3){
                    //팔로우 스타
                    cell.checkButton.selected = [[NSUserDefaults standardUserDefaults] boolForKey:UD_ALARM_STAR];
                }else if(indexPath.row == 4){
                    //무한배틀
                    cell.checkButton.selected = [[NSUserDefaults standardUserDefaults] boolForKey:UD_ALARM_BATTLE];
                }else if(indexPath.row == 5){
                    //관심뉴스
                    cell.checkButton.selected = [[NSUserDefaults standardUserDefaults] boolForKey:UD_ALARM_MY];
                }
                
                //label
//                cell.titleLabel.font = check ? [UIFont systemFontOfSize:14] : [UIFont boldSystemFontOfSize:15];
//                cell.titleLabel.frame = check ? CGRectMake(5, 0, cell.titleLabel.frame.size.width, cell.titleLabel.frame.size.height) :
//                CGRectMake(5, 0, cell.titleLabel.frame.size.width, cell.titleLabel.frame.size.height);
                
            }
            
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else{
            //약관
            
            
            static NSString *CellIdentifier = @"TermTableCell";
            UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
                cell.backgroundColor = [UIColor clearColor];
                
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mySize.width-40, 1)];
                line.backgroundColor = ColorFromRGB(0xc3c2c4);
                [cell.contentView addSubview:line];
                
                UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, tableView.frame.size.width-20, 28)];
                title.backgroundColor = [UIColor clearColor];
                title.textColor = ColorFromRGB(0x49a1d9);
                title.font = [UIFont systemFontOfSize:12];
                title.lineBreakMode = NSLineBreakByWordWrapping;
                title.text = @"개인정보 취급 방침 및 서비스 이용 약관";
                [title sizeToFit];
                [cell.contentView addSubview:title];
                
                UILabel *content = [[UILabel alloc] initWithFrame:CGRectMake(title.frame.origin.x, title.frame.origin.y+title.frame.size.height+11, tableView.frame.size.width-20, 160)];
                content.backgroundColor = [UIColor clearColor];
                content.textColor = ColorFromRGB(0x838387);
                content.font = [UIFont systemFontOfSize:12];
                content.text = @"저작권법 제30조(사적이용을위한복제) 공표된저작물을영리를목적으로하지아니 하고 개인적으로 이용하거나 가정 및 이에 준하는 한정된 범위 안에서 이용하는 경우에 는그이용자는이를복제할수있습니다.\n단,상업적인 목적(홈페이지,블로그 마케팅 등)으로의 사용에 대해서는 ,저작권법에 의해 처벌을 받을 수 있으므로,주의하시기 바랍니다.\n저작물의무단전재및배포시,저작권법136조에의거최고5년이하의징역또는5천만 원이하의 벌금에 처할 수 있습니다.";
                content.numberOfLines = 0;
                [content sizeToFit];
                [cell.contentView addSubview:content];
                
                
            }
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
    else{
        
        static NSString *CellIdentifier = @"restTableViewCell";
        UITableViewCell *cell = (UITableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.backgroundColor = [UIColor clearColor];
            
            
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView.tag == 2) {
        //관심이슈
        NSDictionary *dic = [self.issueArray objectAtIndex:indexPath.row];
        NSString *contentID = [dic objectForKey:@"issue_id"];
//        NSString *newsURL = [dic objectForKey:@"news_url"];
        
        
        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
        
        PhotoViewController *photoController = [[PhotoViewController alloc] init];
        photoController.parentClassIndex = 1;
        photoController.adCount = appDelegate.issueAdCount;
        photoController.mDelegate = self;
        photoController.issuesList = self.issueArray;
        photoController.analyticsAction = ANA_ACT_MY;
        photoController.analyticsLabelDetail = ANA_LAB_My_Issue_Detal;
        photoController.analyticsLabelWhole = ANA_LAB_My_Issue_Whole;
        [photoController setIssueIndex:indexPath.row];
        photoController.typeHotIssue = NO;
        [photoController requestIssueID:contentID];
        [viewController presentModalViewController:photoController animated:YES];
        
    }
    else if (tableView.tag == 3) {
        if (indexPath.section == 0) {
            
            if (indexPath.row == 0) {
                [self appearNoticeView];
            }
            else if (indexPath.row == 7) {
                
                ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
                [viewController appearMail];
            }
        }
    }
}

#pragma mark - UIScrollView Delegate
//다음페이지 이동
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (!duringNetwork) {
        
        if (([scrollView contentOffset].y+scrollView.frame.size.height) == [scrollView contentSize].height) {
            //다음페이지이동
            [self loadNextPage];
        }
    }
    
//    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
//    [viewController sdkHidden:NO];
}

//업데이트
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (!duringNetwork) {
        if (scrollView.contentOffset.y < -50 && issueButton.selected) {
            //업뎃
            [self requestInterestIssueWithPage:1];
        }
    }
    
    if (!decelerate) {
        
//        ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
//        [viewController sdkHidden:NO];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
//    ViewController *viewController = (ViewController*)appDelegate.window.rootViewController;
//    [viewController sdkHidden:YES];
}


@end
